package cn.itcast.mobile;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisMessageContant;
import cn.itcast.entity.Result;
import cn.itcast.utils.SMSUtils;
import cn.itcast.utils.ValidateCodeUtils;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;


    @RequestMapping("/sendCode")
    public Result sendCode(String telephone) {
        // 发送验证码
        Integer valiCode = ValidateCodeUtils.generateValidateCode(4);  // 获取随机4位验证码

        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,valiCode.toString()); //用阿里云发送短信
        // 缓存中保存验证码(5分钟)
            jedisPool.getResource().setex(telephone+RedisMessageContant.SENDTYPE_ORDER,300,valiCode.toString());


        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);

    }

}
